package pers.whj.handler;

public class Looper {
    protected final MessageQueue mQueue;
    private static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<>();

    private Looper() {
        mQueue = new MessageQueue();
    }

    public static void prepare() {
        if (sThreadLocal.get() != null) {
            throw new IllegalStateException("Each thread should not has more than one looper");
        }
        sThreadLocal.set(new Looper());
    }

    public static Looper myLooper() {
        return sThreadLocal.get();
    }

    public static void loop() {
        MessageQueue queue = Looper.myLooper().mQueue;
        while (true) {
            Message msg = queue.next();
            if (msg == null) {
                break;
            }
            msg.target.dispatchMessage(msg);
            msg.recycleUnchecked();
        }
        throw new RuntimeException("Current thread loop unexpectedly exited");
    }
}